package com.example.concurrent.synclock;


import org.aspectj.weaver.ast.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author houyangfan
 * @version 1.0
 * @date 2022/9/28 15:36
 *
 * 不可重入锁的测试，即A方法需要上锁去锁住一段需要
 */
public class NoReentrantLockTest {

    public List<Integer> list = new ArrayList<>();

    Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        NoReentrantLockTest lockTest = new NoReentrantLockTest();
        new Thread("线程1"){
            @Override
            public void run(){
                lockTest.testInsert(Thread.currentThread());
            };
        }.start();

        new Thread("线程2"){
            @Override
            public void run(){
                lockTest.testInsert(Thread.currentThread());
            };
        }.start();
    }

    public void testInsert(Thread thread){

        lock.lock();
        try {
            System.out.println(thread.getName() + "得到了锁");
            if (thread.getName().equals("线程1")) {
                Thread.sleep(2000);
            }
            for (int i = 0; i < 5; i++) {
                list.add(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println(thread.getName() + "释放了锁");
        }

    }
}
